package com.euq.utils;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {
    private static final String SECRET_KEY = "queshiyoudianduanzheyeyoudianduanbushigemenhaibugouma";
    private static final long EXPIRATION_TIME = 1000 * 60 * 60;

    // 生成JWT Token
    public static String generateToken(String account) {
        return Jwts.builder()
                .setSubject(account)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 解析JWT Token
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    // 校验 Token 是否有效
    public static boolean isTokenExpired(String token) {
        Claims claims = parseToken(token);
        return claims.getExpiration().before(new Date());
    }
    public static boolean validateToken(String token) {
        try {
            Claims claims = parseToken(token);
            Date expiration = claims.getExpiration();
            return expiration.after(new Date());
        } catch (ExpiredJwtException e) {
            System.out.println("Token 已过期: " + e.getMessage());
        } catch (UnsupportedJwtException e) {
            System.out.println("不支持的 Token: " + e.getMessage());
        } catch (MalformedJwtException e) {
            System.out.println("Token 格式错误: " + e.getMessage());
        } catch (SignatureException e) {
            System.out.println("Token 签名无效: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println("Token 参数异常: " + e.getMessage());
        }
        return false;
    }
}
